
#include "Clock.h"

#include <cstdio>
#include <iostream>

	/*-----------------------------------------------------------------------*/
	Clock::Clock() : myCurrentValue(0)
	{
		LARGE_INTEGER freq;
		if (!QueryPerformanceFrequency(&freq))
		{
			// Modification by A. Triclot (Segime) for 65860
#ifndef _RTX
		LPVOID lpMsgBuf;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
				(LPTSTR)&lpMsgBuf,0,NULL);
		std::string szLastError((char *)lpMsgBuf);
		LocalFree(lpMsgBuf);
		std::cerr << "QueryPerformanceFrequency not available. Last error is : " << szLastError.c_str() << std::endl;
#endif
			// End of modification by A. Triclot
		}
		tickTime = 1.0 / double(freq.LowPart); /*sec*/
		highTickTime =  double(0x100000000ll) / double(freq.LowPart);
	}

	Clock::~Clock()
	{}

	/*-----------------------------------------------------------------------*/

	bool Clock::init()
	{
		if (!QueryPerformanceCounter(&beginCount))
		{
#ifndef _RTX
		LPVOID lpMsgBuf;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
				(LPTSTR)&lpMsgBuf,0,NULL);
		std::string szLastError((char *)lpMsgBuf);
		LocalFree(lpMsgBuf);
		std::cerr << "QueryPerformanceFrequency not available. Last error is : " << szLastError.c_str() << std::endl;
#endif
			return false;
		}

		myCurrentValue = 0.0;
		return true;
	}

	void Clock::setAbsoluteTime()
	{
		beginCount.LowPart = 0;
		beginCount.HighPart = 0;
	}

	/*-----------------------------------------------------------------------*/

	double Clock::run(void)
	{
		LARGE_INTEGER count;
		QueryPerformanceCounter(&count);

		double deltaLow;
		if (DWORD(count.LowPart) > DWORD(beginCount.LowPart))
			deltaLow = (DWORD(count.LowPart) - DWORD(beginCount.LowPart)) * tickTime;
		else
			deltaLow = - ((DWORD(beginCount.LowPart) - DWORD(count.LowPart)) * tickTime);

		myCurrentValue = deltaLow + (DWORD(count.HighPart) - DWORD(beginCount.HighPart)) * highTickTime;
		return myCurrentValue;
	}

	double Clock::get()
	{
		return myCurrentValue;
	}
